/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.safetytask.service.impl;

import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.safetytask.domain.CustomForm;
import com.koron.safetytask.domain.CustomFormData;
import com.koron.safetytask.domain.UserTask;
import com.koron.safetytask.mapper.CustomFormDataMapper;
import com.koron.safetytask.mapper.CustomFormMapper;
import com.koron.safetytask.mapper.UserTaskMapper;
import com.koron.safetytask.service.api.CustomFormDataService;
import com.koron.safetytask.utils.BusinessCode;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.swan.bean.MessageBean;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CustomFormDataServiceImpl implements CustomFormDataService {

    private final static  Logger logger = LoggerFactory.getLogger(CustomFormServiceImpl.class);

    /**
     * 批量新增
     *
     * @param beanList
     * @return
     */
    @Override
    public MessageBean<Integer> batchInsert(List<CustomFormData> beanList) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "保存成功", Integer.class);
        try (SessionFactory factory = new SessionFactory()) {
            if (null != beanList && beanList.size() > 0) {
                for (CustomFormData customFormData : beanList) {
                    if (StringUtils.isEmpty(customFormData.getId())) {
                        customFormData.setId(DefaultIdGenerator.getInstance().generateLongId());
                    }
                }
                //批量添加自定义表单数据
                Integer integer = factory.getMapper(CustomFormDataMapper.class).batchInsert(beanList);
                if (integer <= 0) {
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("保存失败");
                }
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    /**
     * 批量修改自定义表单数据
     *
     * @param beanList
     * @return
     */
    @Override
    public MessageBean<Integer> batchUpdate(List<CustomFormData> beanList) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "保存成功", Integer.class);
        try (SessionFactory factory = new SessionFactory()) {
            List<CustomFormData> addList = new ArrayList<>();
            List<CustomFormData> updateList = new ArrayList<>();
            if (null != beanList && beanList.size() > 0) {
                // 先找出新增的数据和更新的数据
                for (CustomFormData customFormData : beanList) {
                    if (StringUtils.isEmpty(customFormData.getId())) {
                        addList.add(customFormData);
                    } else {
                        updateList.add(customFormData);
                    }
                }
                for (CustomFormData customFormData : addList) {
                    customFormData.setId(DefaultIdGenerator.getInstance().generateLongId());
                    customFormData.setAddUser(customFormData.getUpdateUser());
                    customFormData.setAddUserName(customFormData.getUpdateUserName());
                    customFormData.setAddTime(customFormData.getUpdateTime());
                }
                if (null != addList && addList.size() > 0) {
                    factory.getMapper(CustomFormDataMapper.class).batchInsert(addList);
                }
                Integer integer = factory.getMapper(CustomFormDataMapper.class).batchUpdate(updateList);
                if (integer <= 0) {
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("保存失败");
                }
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }

    }

    /**
     * 批量删除自定义表单数据
     *
     * @param idList 需删除的数据id集合
     * @return
     */
    @Override
    public MessageBean<Integer> batchDelete(List<String> idList) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "删除成功", Integer.class);
        try (SessionFactory factory = new SessionFactory()) {
            if (null != idList && idList.size() > 0) {
                Integer integer = factory.getMapper(CustomFormDataMapper.class).batchDelete(idList);
                if (integer <= 0) {
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("删除失败");
                }
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    /**
     * 查询表格数据详情
     *
     * @param tbaleCode   表格编码
     * @param addUser     添加人code
     * @param addUserName 添加人name
     * @param start       开始页
     * @param rows        每页条数
     * @return
     */
    @Override
    public MessageBean<DataBean<List<Map>>> queryByCondition(String tbaleCode, String businessId, String addUser, String addUserName, Integer start, Integer rows) {
        MessageBean<DataBean<List<Map>>> msg = new MessageBean<>();
        List<List<Map>> data = new ArrayList<>();
        SimpleDateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try (SessionFactory factory = new SessionFactory()) {
            Map map = new HashMap();
            map.put("tbaleCode", tbaleCode);
            map.put("businessId", businessId);
            map.put("addUser", addUser);
            map.put("addUserName", addUserName);
            List<Map> list = factory.getMapper(CustomFormDataMapper.class).queryByCondition(map);
            if (null != list && list.size() > 0) {
                for (Map map1 : list) {
                    Integer keyType = (Integer) map1.get("keyType");
                    if (keyType == 3) {
                        String keyValue = (String) map1.get("keyValue");
                        map1.put("keyValue", Integer.valueOf(keyValue));
                    }
                }
                // 根据表格行id对数据进行分组
                Map<Object, List<Map>> collect = list.stream().collect(Collectors.groupingBy(map1 -> map1.get("rowId")));
                for (Object o : collect.keySet()) {
                    List<Map> maps = collect.get(o);
                    data.add(maps);
                }
                for (List<Map> datum : data) {
                    for (int i = 0; i < datum.size(); i++) {
                        datum.get(i).put("keyCode", "key" + i);
                    }
                }
            }
            Integer end = (start == 0 ? rows : start + rows);
            if (end > data.size()) {
                end = data.size();
            }
            Integer totalNumber = data.size();
            Integer totalPage = totalNumber > rows ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            DataBean<List<Map>> dataBean = new DataBean<>();
            dataBean.setList(data.subList(start, end));
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setPageSize(rows);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询自定义表单数据成功");
            msg.setData(dataBean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    /**
     * 自定义表单导出
     *
     * @param tbaleCode 表格编码
     * @return
     */
    @Override
    public MessageBean<LinkedHashMap> details(String tbaleCode, String businessId) {
        MessageBean<LinkedHashMap> msg = new MessageBean<>();
        List<List<Object>> dataList = new ArrayList<>();
        LinkedHashMap retMap = new LinkedHashMap<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<CustomForm> customFormList = factory.getMapper(CustomFormMapper.class).queryAllKeyName(tbaleCode);
            // 获取所有表头字段
            List<String> keyNameList = new ArrayList<>();
            for (CustomForm customForm : customFormList) {
                keyNameList.add(customForm.getKeyName());
            }
            if (keyNameList.isEmpty()) {
                msg.setCode(-1);
                msg.setDescription("表格不存在");
                return msg;
            }
            String name = customFormList.get(0).getName();
            Map map = new HashMap();
            map.put("tbaleCode", tbaleCode);
            map.put("businessId", businessId);
            List<Map> list = factory.getMapper(CustomFormDataMapper.class).queryDetails(map);
            HashMap<String, Double> totalMap = new HashMap<>();
            // 根据字段类型对数据做处理
            if (null != list && list.size() > 0) {
                for (Map map1 : list) {
                    Integer keyType = (Integer) map1.get("keyType");
                    // 判断是否为枚举，并赋枚举值
                    if (keyType == 3) {
                        String enumValue = (String) map1.get("enumValue");
                        String[] split = enumValue.split("[,，]");
                        String keyValue = (String) map1.get("keyValue");
                        Integer value = Integer.valueOf(keyValue);
                        map1.put("keyValue", split[value - 1]);
                    }
                }
                //数字类型的表单数据
                List<Map> numTypeRes = list.stream().filter(m -> 2 == (Integer) m.get("keyType")).collect(Collectors.toList());
                Map<Object, List<Map>> numTypeGroupByKeyName = numTypeRes.stream().collect(Collectors.groupingBy(mm -> mm.get("keyName")));
                numTypeGroupByKeyName.entrySet().forEach(en->{
                    Double sum = 0.0;
                    for (Map map1 : en.getValue()) {
                        sum += Double.valueOf((String) map1.get("keyValue"));
                    }
                    totalMap.put((String)en.getKey(),sum);
                });
                Map<Object, List<Map>> collect = list.stream().collect(Collectors.groupingBy(map1 -> map1.get("rowId")));
                // 根据表格行id对数据进行分组
                for (Object o : collect.keySet()) {
                    List<Object> keyValue = collect.get(o).stream().map(map1 -> map1.get("keyValue")).collect(Collectors.toList());
                    dataList.add(keyValue);
                }
            }
            if (dataList.isEmpty()) {
                retMap.put("dataList", new ArrayList<>());
                retMap.put("keyNameList", keyNameList);
                retMap.put("name", name);
                msg.setData(retMap);
                return msg;
            }
            retMap.put("dataList", dataList);
            retMap.put("keyNameList", keyNameList);
            retMap.put("name", name);
            //统计数据
            retMap.put("total", totalMap);
            msg.setData(retMap);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    /**
     * 根据表格编码和关联业务id查询最高rowId
     *
     * @param tbaleCode  表格编码
     * @param userTaskId 关联业务id
     * @return
     */
    @Override
    public MessageBean<Integer> queryMaxRow(String tbaleCode, String userTaskId) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Integer.class);
        try (SessionFactory factory = new SessionFactory()) {
            Integer integer = factory.getMapper(CustomFormDataMapper.class).queryMaxRowId(tbaleCode, userTaskId);
            msg.setData(integer);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    /**
     * @MethodName: queryAllByCondition
     * @Description: 查询当前任务下面所有已有得表格数据并传给前端
     * @Param: [tbaleCode, businessId, start, rows]
     * @Author: LRL
     * @Date: 2020/7/24 17:11
     */
    public MessageBean<DataBean<List<Map>>> queryAllByCondition(StaffBean user,
                                                                String tbaleCode,
                                                                String businessId,
                                                                Integer start,
                                                                Integer rows,String addUser,String addUserName) {
        MessageBean<DataBean<List<Map>>> msg = new MessageBean<>();
        List<List<Map>> data = new ArrayList<>();
        try (SessionFactory factory = new SessionFactory()) {
            //todo 判断是不是包含执行人  如果不是就只查询本执行人的数据
            UserTaskMapper userTaskMapper = factory.getMapper(UserTaskMapper.class);
            UserTask userTask = userTaskMapper.queryOne(businessId);
            Map map = new HashMap();
            map.put("tbaleCode", tbaleCode);
            map.put("businessId", businessId);
            //是不是发起人
            boolean initFlag = !userTask.getInitiatorCode().equals(addUser);
            if (initFlag) {
                map.put("addUser", addUser);
                map.put("addUserName", addUserName);
            }
            boolean recFlag = !userTask.getReceiverCode().contains(addUser);
            //既不是发起人也不是执行人
            if (recFlag && initFlag) {
                msg.setCode(BusinessCode.ACCESS_DENY_NOT_USER.getCode());
                msg.setDescription(BusinessCode.ACCESS_DENY_NOT_USER.getDescription());
                return msg;
            }
            CustomFormDataMapper mapper = factory.getMapper(CustomFormDataMapper.class);
            List<Map> list = mapper.queryByCondition(map);
            if (null != list && list.size() > 0) {
                for (Map map1 : list) {
                    Integer keyType = (Integer) map1.get("keyType");
                    if (keyType == 3) {
                        String keyValue = (String) map1.get("keyValue");
                        map1.put("keyValue", Integer.valueOf(keyValue));
                    }
                }
                // 根据表格行id对数据进行分组 有序分组
                LinkedHashMap<Object, List<Map>> collect = list.stream().collect(Collectors.groupingBy(map1 -> map1.get("rowId"), LinkedHashMap::new, Collectors.toList()));
                for (Object o : collect.keySet()) {
                    List<Map> maps = collect.get(o);
                    data.add(maps);
                }
                for (List<Map> datum : data) {
                    for (int i = 0; i < datum.size(); i++) {
                        datum.get(i).put("keyCode", "key" + i);
                    }
                }
            }
            Integer end = (start == 0 ? rows : start + rows);
            if (end > data.size()) {
                end = data.size();
            }
            Integer totalNumber = data.size();
            Integer totalPage = totalNumber > rows ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            DataBean<List<Map>> dataBean = new DataBean<>();
            dataBean.setList(data.subList(start, end));
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setPageSize(rows);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询自定义表单数据成功");
            msg.setData(dataBean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }
}
